
package com.jz.listener;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jz.util.SpringContextUtil;


public class WebStartupListener extends ContextLoaderListener implements ServletContextListener {

	private static final Log log = LogFactory.getLog(WebStartupListener.class);

	public void contextInitialized(ServletContextEvent event) {
		if (log.isDebugEnabled()) {
			log.debug("Initializing context...");
		}

		ServletContext context = event.getServletContext();

		if (log.isDebugEnabled()) {
			log.debug("Loading application configurations......");
		}

		if (log.isDebugEnabled()) {
			log.debug("Initializing spring application context...");
		}

		// super.contextInitialized(event);

		initSystemSingleObjects(); // 初始化各个需要提前初始化的单例对象。

		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

		/*
		 * try { List urlSecurityList = urlControlManager.getUrlControl(); if
		 * (urlSecurityList == null) { UrlControlUtil.initUrlSecurityMap(new
		 * ArrayList()); } else {
		 * UrlControlUtil.initUrlSecurityMap(urlSecurityList); } } catch
		 * (Exception e) { UrlControlUtil.initUrlSecurityMap(null); }
		 */
		SpringContextUtil.setSpringContext(ctx);
		ApplicationInit.initDataCake(ctx);
	}

	public void initSystemSingleObjects() {
		// SessionManagerFactory.initialize();

		String serverHome = WebStartupListener.class.getResource("/").getPath();
		String configDir = serverHome + File.separator;

		if (!configDir.endsWith(File.separator)) {
			configDir += File.separator;
		}

		initLoggingSystem(configDir);
	}

	private void initLoggingSystem(String configDir) {
		File log4jConfigFile = new File(configDir, "log4j.properties");
		System.setProperty("log.dir", configDir);
		if (log4jConfigFile.exists()) {
			PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath());
		}
	}
}
